import config from '../config'

let
    pixelRatio = window.devicePixelRatio,
    windowWidth = window.innerWidth,
    windowHeight = window.innerHeight,
    canvas = document.querySelector('canvas')

if (window.innerHeight > window.innerWidth) {
    windowWidth = window.innerHeight
    windowHeight = window.innerWidth

    canvas.style.width = `${windowWidth}px`
    canvas.style.height = `${windowHeight}px`
    canvas.style.top = `${(innerHeight - windowHeight) * .5}px`
    canvas.style.left = `${(innerWidth - windowWidth) * .5}px`
}

PIXI.interaction.InteractionManager.prototype.mapPositionToPoint = function(point, x, y) {
    let rect

    // IE 11 fix
    if (!this.interactionDOMElement.parentElement) {
        rect = {x: 0, y: 0, width: 0, height: 0}
    } else {
        rect = this.interactionDOMElement.getBoundingClientRect()
    }

    const resolutionMultiplier = navigator.isCocoonJS ? this.resolution : (1.0 / this.resolution)

    /*
    * 特殊处理: 强制横屏情况
    */
    if (window.orientation === 0) {
        point.x = (y - rect.top) * (this.interactionDOMElement.width / rect.height) * resolutionMultiplier
        point.y = (1 - (x - rect.left) / rect.width) * this.interactionDOMElement.height * resolutionMultiplier
    } else {
        point.x = ((x - rect.left) * (this.interactionDOMElement.width / rect.width)) * resolutionMultiplier
        point.y = ((y - rect.top) * (this.interactionDOMElement.height / rect.height)) * resolutionMultiplier
    }
}

config.screen.width = windowWidth * pixelRatio
config.screen.height = windowHeight * pixelRatio
config.zoom = Math.min(config.screen.width / config.width, config.screen.height / config.height)

const app = new PIXI.Application({
    width: config.screen.width,
    height: config.screen.height,
    view: canvas,
    transparent: true, // 必须
    antialias: false,
    roundPixels: true
})

// app.stage.scale.set(config.zoom)



export default app
export {default as Tilemap} from './tilemap/index'
export const monitor = new PIXI.utils.EventEmitter()

